package menus_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"

	"github.com/gin-gonic/gin"
)

func (MenusApi) MenusModifyView(c *gin.Context) {
	var cr MenusRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}
	id := c.Param("id")
	// 先清理 banner 内容
	var menusModel models.MenuModel
	err = common.DB.Debug().Take(&menusModel, id).Error
	if err != nil {
		http.FailWithMessage("菜单不存在", c)
		return
	}
	err = common.DB.Debug().Model(&menusModel).Association("BannerImages").Clear()
	if err != nil {
		http.FailWithMessage("菜单不存在", c)
		return
	}
	// 判断是否存在图片
	if len(cr.ImageSortList) > 0 {
		// 给第三张入库
		menuBannerList := make([]*models.MenuBannerModel, 0)
		for _, sort := range cr.ImageSortList {
			// 需要判断图片是否存在
			menuBannerList = append(menuBannerList, &models.MenuBannerModel{
				MenuID:   menusModel.ID,
				BannerID: sort.ImageID,
				Sort:     sort.Sort,
			})
		}
		err = common.DB.Create(&menuBannerList).Error
		if err != nil {
			common.Log.Error(err.Error())
			http.FailWithMessage("菜单图片保存失败", c)
			return
		}
	}
	menusUpdate := &models.MenuModel{
		Title:           cr.Title,
		Path:            cr.Path,
		Slogan:          cr.Slogan,
		Information:     cr.Information,
		InformationTime: cr.InformationTime,
		BannerTime:      cr.BannerTime,
		Sort:            cr.Sort,
	}
	err = common.DB.Where("id = ?", id).Updates(&menusUpdate).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("菜单修改失败", c)
		return
	}
	http.IsOkWithMessage("菜单修改成功", c)
}
